package com.boco.wmworkflow.common.util;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import com.boco.common.util.io.*;
import org.w3c.dom.Document;

public class XsltHelper {
    private XsltHelper() {
    }

    public static byte[] prepareHTMLReport(String xsltFilePath, byte[] xmlBytes) {
        BufOutputStream htmlBytes = new BufOutputStream();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dbf.newDocumentBuilder();

            Document document = builder.parse(new BufInputStream(xmlBytes));
            DOMSource xmlSource = new DOMSource(document);

            InputStream in = FileHelper.getFileStream(xsltFilePath);
            StreamSource xslSource = new StreamSource(in);

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer(xslSource);
            StreamResult result = new StreamResult(htmlBytes);
            transformer.transform(xmlSource, result);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return htmlBytes.getBuf();
    }
}
